/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bemanager.util;

import com.inspur.edp.bcc.billcategory.api.BillCategoryService;
import com.inspur.edp.bcc.billcategory.entity.billcategorydef.BillCategory;
import com.inspur.edp.bcc.billcategory.entity.billcategorydef.beinfo.BeInfo;
import com.inspur.edp.bcc.billcategory.server.api.BillCategoryServerService;
import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.bef.bizentity.util.StringUtil;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.metadata.businesstype.api.MdBizTypeMappingService;
import com.inspur.edp.wf.bizprocess.entity.FlowFormPayload;
import com.inspur.edp.wf.bizprocess.service.FlowFormRpcService;
import io.iec.edp.caf.businessobject.api.service.DevBasicInfoService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.rpc.client.RpcClassHolder;
import java.util.HashMap;
import java.util.List;

public class BeGuideUtil {

  private BeGuideUtil() {
  }

  private static BeGuideUtil instance;

  public static BeGuideUtil getInstance() {
    if (instance == null) {
      instance = new BeGuideUtil();
    }
    return instance;
  }

  /**
   * 获取业务种类Id
   */
  public String getBizTypeId(String boId) {
    List<String> bizTypeIds = SpringBeanUtils.getBean(MdBizTypeMappingService.class)
        .getBizTypeIdsByBoId(boId);
    if (bizTypeIds == null || bizTypeIds.size() < 1) {
      return null;
    }
    for (String bizTypeId : bizTypeIds) {
      if (checkValidBillCategory(bizTypeId)) {
        return bizTypeId;
      }
    }
    throw new RuntimeException("根据Bo获取业务种类ID失败，请在业务种类菜单中新增业务种类，在业务种类的元数据功能页签新增元数据并关联当前BO");
  }

  private boolean checkValidBillCategory(String bizTypeId) {
    BillCategory billCategory = SpringBeanUtils.getBean(BillCategoryService.class)
        .getBillCategory(bizTypeId);
    return billCategory != null;
  }

  /**
   * 给RPC调用传值
   */
  public boolean precastFlowFormPayload(GspMetadata metadata) {
    GspBusinessEntity bizEntity = (GspBusinessEntity) metadata.getContent();
    //判断是否启用入口单据
    // todo: 依赖
//    if(!bizEntity.getEnableApproval())
//      return false;
    String boId = metadata.getHeader().getBizobjectID();
    String suCode = SpringBeanUtils.getBean(DevBasicInfoService.class).getDevBasicBoInfo(boId)
        .getSuCode();

    if (StringUtil.checkNull(suCode)) {
      throw new RuntimeException("根据Bo获取SU失败，BO Id: " + boId);
    }
    FlowFormPayload flowFormPayload = new FlowFormPayload();
    String bizTypeId = getBizTypeId(boId);
    if (StringUtil.checkNull(bizTypeId)) {
      return false;
    }
    // SU Code
    flowFormPayload.setSu(suCode);
    // 业务种类ID
    flowFormPayload.setBizCategoryId(bizTypeId);
    // 元数据ID
    flowFormPayload.setSchemaMetadataId(metadata.getHeader().getId());
    // 节点Id 编号 名称
    flowFormPayload.setSchemaId(bizEntity.getMainObject().getID());
    flowFormPayload.setSchemaCode(bizEntity.getMainObject().getCode());
    flowFormPayload.setSchemaName(bizEntity.getMainObject().getName());
    // 不设置是内置工作流
    flowFormPayload.setSysInit(0);

    //RPC强类型调用
    RpcClassHolder rpcClassHolder = SpringBeanUtils.getBean(RpcClassHolder.class);
    FlowFormRpcService flowFormRpcService = rpcClassHolder.getRpcClass(FlowFormRpcService.class);
    flowFormRpcService.addFlowForm(flowFormPayload);

    BeInfo beInfo = new BeInfo();
    beInfo.setId(bizEntity.getID());
    beInfo.setCode(bizEntity.getCode());
    beInfo.setName(bizEntity.getName());

    setBizTypeState(bizTypeId, beInfo);

    return true;
  }

  /**
   * 判断当前BO下是否存在业务种类
   *
   * @param boId
   * @return
   */
  public boolean bizObjectContainBizType(String boId) {
    String bizTypeId = getBizTypeId(boId);
    return !StringUtil.checkNull(bizTypeId);
  }

  /*
   * 启用流程配置并添加在关联业务种类中业务实体
   */
  private void setBizTypeState(String bizTypeId, BeInfo info) {
    BillCategoryServerService serverService = SpringBeanUtils
        .getBean(BillCategoryServerService.class);
    serverService.saveBillCategory(bizTypeId, "processAssignManager", true);
    BillCategory billCategory = serverService.getBillCategory(bizTypeId);
    if (billCategory.getTargetBeId() == null || billCategory.getTargetBeId().length() == 0) {
      billCategory.setTargetBeInfo(info);
      serverService.saveBillCategory(billCategory, new HashMap<>());
    }

  }

}
